<template>
  <uv-upload
    v-bind="$attrs"
    :fileList="fileList"
    :maxCount="3"
    multiple
    name="3"
    @delete="deletePic"
    @afterRead="afterRead"
  ></uv-upload>
</template>

<script setup>
import { computed } from "vue"
import { baseUrl } from "/http/baseUrl"
import { userInfo } from "/store/userInfo/index.js"
import { storeToRefs } from "pinia"

const store = userInfo()
const { state } = storeToRefs(store)

const props = defineProps({
  fileList: {
    type: Array,
    default: () => []
  }
})
const emits = defineEmits(["upload:fileList"])

const newFileList = computed(() => props.fileList)

const afterRead = async (event) => {
  const files = [].concat(event.file)
  let fileListLen = newFileList.value.length
  for (let i = 0; i < files.length; i++) {
    newFileList.value.push({
      ...files[i],
      status: "uploading",
      message: "上传中"
    })
    const result = await uploadFilePromise(files[i].url)
    let item = newFileList.value[fileListLen]
    newFileList.value.splice(
      fileListLen,
      1,
      Object.assign(item, {
        status: "success",
        message: "上传成功",
        url: result.url
      })
    )
    fileListLen++
    emits("upload:fileList", newFileList.value)
  }
}
const uploadFilePromise = (url) => {
  return new Promise((resolve, reject) => {
    uni.uploadFile({
      url: baseUrl + "/common/upload", // 仅为示例，非真实的接口地址
      filePath: url,
      name: "file",
      header: {
        Authorization: "Bearer " + state.value.info?.token
      },
      formData: {
        user: "test"
      },
      success: (res) => {
        if (res.statusCode === 200) {
          resolve(JSON.parse(res.data))
        }
      }
    })
  })
}

// 删除图片
const deletePic = (event) => {
  newFileList.value.splice(event.index, 1)
  emits("upload:fileList", newFileList.value)
}
</script>

<style lang="scss" scoped></style>
